//$URL: http://deveth0.googlecode.com/svn/trunk/demos/jersey-springsecurity/src/main/java/de/deveth0/demos/jerseyspringsecurity/security/contextfilter/UserIdCheckContextFilter.java $
//$Id: UserIdCheckContextFilter.java 6 2012-10-24 20:07:15Z amuthmann@gmail.com $
/*
 * Copyright 2012 deveth0.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.deveth0.demos.jerseyspringsecurity.security.contextfilter;

import javax.ws.rs.ext.Provider;



import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import com.sun.jersey.spi.container.ContainerResponseFilter;
import com.sun.jersey.spi.container.ResourceFilter;
import de.deveth0.demos.jerseyspringsecurity.data.User;
import de.deveth0.demos.jerseyspringsecurity.security.UserSecurityContext;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Filter that checks if the accessing user has the same id as the requested path.
 *
 * @author deveth0
 *
 */
@Provider    // register as jersey's provider
public class UserIdCheckContextFilter implements ResourceFilter, ContainerRequestFilter {

  private final UriInfo mUriInfo;

  public UserIdCheckContextFilter(UriInfo pUriInfo) {
    this.mUriInfo = pUriInfo;
  }

  @Override
  public ContainerRequest filter(ContainerRequest pRequest) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    Object principle = authentication == null ? null : authentication.getPrincipal();
    if (principle != null && principle instanceof User) {
      User user = (User) principle;
      String requestId = mUriInfo.getPathParameters().get("id").get(0);
      if (StringUtils.equals(user.getUserId(), requestId)) {
        pRequest.setSecurityContext(new UserSecurityContext(user));
        return pRequest;
      } else {
        throw new WebApplicationException(Response.Status.FORBIDDEN);
      }
    }
    throw new WebApplicationException(Response.Status.UNAUTHORIZED);
  }

  @Override
  public ContainerRequestFilter getRequestFilter() {
    return this;
  }

  @Override
  public ContainerResponseFilter getResponseFilter() {
    return null;
  }
}